﻿using Mforj.Common.Utils;
using smforj.common.dao;
using smforj.common.model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace smforj.common.service
{
    /// <summary>
    /// 试衣间操作Service
    /// </summary>
    public interface IFittingService : IUpload
    {
        /// <summary>
        /// 根据编码查询商品信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>商品信息列表</returns>
        List<Commodity> GetCommoditysRemote(IQuery query);

        /// <summary>
        /// 根据编码查询商品信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>商品信息列表</returns>
        Commodity GetCommodityRemote(IQuery query);

        /// <summary>
        /// 查询商品类型
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>商品信息列表</returns>
        List<CommodityType> GetCommodityTypeRemote(IQuery query);

        /// <summary>
        /// 推送要显示的信息
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        int SendFitting(List<Fitting> models);

        /// <summary>
        /// 批量保存商品喜好信息
        /// </summary>
        /// <param name="Fittings"></param>
        void SaveFittings(List<Fitting> Fittings);

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="image"></param>
        void DownloadImage(String image);



        /// <summary>
        /// 根据位置信息查询要显示的信息
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        List<Collocation> GetCollocationLocal(String location);
    }


    /// <summary>
    /// 试衣间操作Service实现
    /// </summary>
    public class FittingServiceImpl : IFittingService
    {
        private IFittingDao fittingDao = new FittingSqliteDaoImpl();

        public FittingServiceImpl()
        { 
        } 

        private static HttpHelper httpHelper = new HttpHelper();
        private static JsonHelper jsonHelper = new JsonHelper();
        /// <summary>
        /// 查询商品信息，要通过接口
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <returns></returns>
        public model.Commodity GetCommodityRemote(model.IQuery query)
        {

            String url = query.GetUrl() + "?token=" + GlobalCache.loginUser.access_token +"&rfid="+query.GetID();
            String response = httpHelper.GetRequestJson(url);

            CommodityResponse cres = jsonHelper.JsonDeSerializer<CommodityResponse>(response);
            if (cres == null)
                cres = new CommodityResponse() { isSuccess = false, message = "return data Exception" };

            if (cres.isSuccess)
                return (Commodity)cres.GetData();

            return null;
        }


        /// <summary>
        /// Clones the specified list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="List">The list.</param>
        /// <returns>List{``0}.</returns>
        public static List<T> Clone<T>(object List)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, List);
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as List<T>;
            }
        }

        private int SortByType(Fitting obj1, Fitting obj2)
        {
            int res = 0;
            if ((obj1 == null) && (obj2 == null))
            {
                return 0;
            }
            else if ((obj1 != null) && (obj2 == null))
            {
                return 1;
            }
            else if ((obj1 == null) && (obj2 != null))
            {
                return -1;
            }
            if ((obj1.Type == null) && (obj2.Type == null))
            {
                return 0;
            }
            else if ((obj1.Type != null) && (obj2.Type == null))
            {
                return 1;
            }
            else if ((obj1.Type == null) && (obj2.Type != null))
            {
                return -1;
            }
            else if (Convert.ToInt32(obj1.Type.order) > Convert.ToInt32(obj2.Type.order))
            {
                res = 1;
            }
            else if (Convert.ToInt32(obj1.Type.order) < Convert.ToInt32(obj2.Type.order))
            {
                res = -1;
            }
            if (obj1.Type.order.CompareTo(obj2.Type.order) < 0)
                res = -1;
            else
                res = 1;
            return res;
        }

        private static int iCount = 0;

        /// <summary>
        /// 上传已经采集到的数据信息到服务器
        /// </summary>
        /// <returns></returns>
        public int UploadData()
        {

            //上传商品推荐信息
            //查询所有商品推荐信息
            FittingQuery query = new FittingQuery();
            List<Recommend> list = fittingDao.GetRecommendsLocal(query);

            if (list != null && list.Count > 0)
            {
                iCount++;
                Console.WriteLine("uploaddata...." + iCount);
                String url = GlobalCache.UploadRecommendUrl;
                UploadRecommend upload = new UploadRecommend();
                upload.deviceID = GlobalCache.DeviceID;
                upload.storeID = GlobalCache.StoreID;
                upload.token = GlobalCache.loginUser.access_token;

                upload.data = list.ToArray();


                String data = jsonHelper.JsonSerializer<UploadRecommend>(upload);
                //上传 
                String response = httpHelper.PostRequestJson(url, data);


                UploadRecommendResponse cres = jsonHelper.JsonDeSerializer<UploadRecommendResponse>(response);

                if (cres == null)
                    cres = new UploadRecommendResponse() { isSuccess = false, message = "return data Exception" };
                if (cres.isSuccess)
                {

                    foreach (Recommend model in list)
                        //删除
                        fittingDao.DeleteById(model.id);
                    return 1;
                }
            }
            return -1;
        }


        /// <summary>
        /// 批量保存商品推荐信息
        /// </summary>
        /// <param name="Fittings"></param>
        public void SaveFittings(List<model.Fitting> Fittings)
        {
            if (Fittings != null)
            {
                List<Recommend> list = new List<Recommend>();
                //只有大于1的消息才进行推荐保存
                if (Fittings.Count > 1)
                {
                    //排序
                    Fittings.Sort(SortByType);
                    //是否是多个类型的衣服
                    List<CommodityType> tType = new List<CommodityType>();
                    foreach (Fitting fit in Fittings)
                    {
                        if (tType.Count < 1)
                        {
                            tType.Add(fit.Type);
                            continue;
                        }
                        CommodityType type = tType.Find(t => t.name == fit.Type.name);
                        if (null == type)
                            tType.Add(fit.Type);
                    }
                    //类型排序
                    //tType.Sort();
                    //有多种类型的商品
                    if (tType.Count > 1)
                    {
                        //赋值Index
                        int index = 0;
                        int iCount = 0;
                        String remark = "Fitting Room Data";
                        for (int i = 0; i < tType.Count; i++)
                        {
                            String type = tType[i].name;
                            List<Fitting> temp = Fittings.FindAll(z => z.Type.name == type);
                            DateTime date = DateTime.Now;

                            //如果已经有数据则用原数据copy temp.count份
                            if (i == 0)
                            {
                                for (int m = 0; m < temp.Count; m++)
                                    list.Add(new Recommend() { rfid1 = temp[m].RFID, create_date = date, update_date = date, remark = remark });
                                continue;
                            }
                            else
                            {

                                //如果每种数据只有一个则只有一个组合,i等于1时不进行处理
                                if (Fittings.Count != tType.Count)
                                {
                                    iCount = list.Count;
                                    List<Recommend> t = new List<Recommend>();
                                    for (int m = 0; m < temp.Count - 1; m++)
                                    {
                                        for (int n = 0; n < list.Count; n++)
                                            t.Add(new Recommend()
                                            {
                                                rfid1 = list[n].rfid1,
                                                rfid2 = list[n].rfid2,
                                                rfid3 = list[n].rfid3,
                                                rfid4 = list[n].rfid4,
                                                rfid5 = list[n].rfid5,
                                                create_date = date,
                                                update_date = date,
                                                remark = remark
                                            });
                                    }
                                    list.AddRange(t.ToArray());
                                }
                                else
                                {
                                    iCount = 1;
                                }
                            }
                            for (int m = 0; m < temp.Count; m++)
                            {
                                Fitting fit = temp[m];
                                index = m * iCount;
                                for (int n = index; n < (iCount + index); n++)
                                {
                                    Recommend model = list[n];
                                    switch (i)
                                    {
                                        case 0:
                                            model.rfid1 = fit.RFID;
                                            break;
                                        case 1:
                                            model.rfid2 = fit.RFID;
                                            break;
                                        case 2:
                                            model.rfid3 = fit.RFID;
                                            break;
                                        case 3:
                                            model.rfid4 = fit.RFID;
                                            break;
                                        case 4:
                                            model.rfid5 = fit.RFID;
                                            break;
                                    }
                                }
                            }

                        }
                    }
                    if (list.Count > 0) fittingDao.SaveBatch(list);
                }
            }
        } 

        /// <summary>
        /// 从服务器下载推荐信息并保存到本地
        /// </summary>
        /// <param name="models">Fitting信息</param>
        /// <returns></returns>
        public int SendFitting(List<Fitting> models)
        {

            //GlobalCache.colList.RemoveAll(z => z.FittingNum == model.AntnnaNumber);
            List<Collocation> clist = new List<Collocation>();
            foreach (Fitting model in models)
            {
                //远程下载搭配信息
                String url = GlobalCache.RankingUrl + "?token=" + GlobalCache.loginUser.access_token + "&storeid=" + model.Loaction + "&top=10&rfid=" + model.RFID;
                String response = httpHelper.GetRequestJson(url);

                RankingResponse cres = jsonHelper.JsonDeSerializer<RankingResponse>(response);
                if (cres == null)
                    cres = new RankingResponse() { isSuccess = false, message = "return data Exception" };

                List<model.RankingVo> list = new List<model.RankingVo>();
                if (cres.isSuccess)
                    list.AddRange((RankingVo[])cres.GetData());

                //下载并显示商品信息
                Commodity com = this.GetCommodityRemote(new FittingQuery() { Url = GlobalCache.CommodityUrl, RFID = model.RFID });
                Collocation col = clist.Find(z => z.ID == com.id);
                if (col == null)
                {
                    try
                    {
                        //下载图片
                        if (!com.image.StartsWith("/"))
                            com.image = "/" + com.image;
                        DownloadImage(GlobalCache.BaseUrl + com.image);
                    }
                    catch { }

                    String image = Path.Combine(GlobalCache.BaseImgPath, Path.GetFileName(com.image));
                    col = new Collocation();
                    col.ID = com.id;
                    col.Name = com.name;
                    col.Loaction = model.Loaction;
                    col.FittingNum = model.AntnnaNumber;
                    col.RFID = com.rfid;
                    col.image = image;
                    col.Type = com.type;
                    col.Order = model.Type == null ? 0 : model.Type.order;
                    clist.Add(col);
                }

                //有搭配信息
                if (list.Count > 0)
                {
                    foreach (RankingVo vo in list)
                    {
                        col = clist.Find(z => z.ID == vo.id);
                        //每个搭配信息只需要一张图片多余的不要
                        if (col == null && !String.IsNullOrEmpty(vo.images))
                        {
                            String[] images = vo.images.Split('|');
                            StringBuilder sb = new StringBuilder();
                            foreach(String str in images)
                            {
                                String spath = str;
                                try
                                {
                                    //下载图片
                                    if (!spath.StartsWith("/"))
                                        spath = "/" + spath;
                                    DownloadImage(GlobalCache.BaseUrl + spath);

                                    sb.Append(spath);
                                    break;
                                }
                                catch { }  

                            }
                             
                            col = new Collocation();
                            col.ID = vo.id;
                            col.Name = model.Loaction;
                            col.Loaction = model.Loaction;
                            col.FittingNum = model.AntnnaNumber;
                            col.RFID = model.RFID;
                            col.image = sb.ToString();
                            col.Type = "";
                            col.Order = 0;
                            clist.Add(col);
                        } 
                    }
                } 
        
                //GlobalCache.colList.AddRange(clist);

            }
            return this.fittingDao.SaveCollocationBatch(clist);
        } 


        /// <summary>
        /// 根据位置信息查询要显示的信息
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        public List<Collocation> GetCollocationLocal(String location)
        {
            return this.fittingDao.GetCollocationList(location);
        }

        /// <summary>
        /// 下载图片信息
        /// </summary>
        /// <param name="image"></param>
        public void DownloadImage(string image)
        {
            String imagename = Path.GetFileName(image);
            //已经存在则不再下载
            if (CheckImage(imagename))
                return;

            String path = Path.Combine(GlobalCache.BaseImgPath, imagename);
            httpHelper.DownloadFile(image, path);
        }


        private Boolean CheckImage(String imagename)
        {
            //不存在则创建
            if (!Directory.Exists(GlobalCache.BaseImgPath))
                Directory.CreateDirectory(GlobalCache.BaseImgPath);
            String path = Path.Combine(GlobalCache.BaseImgPath, imagename);

            return File.Exists(path);
        }



        /// <summary>
        /// 查询远程商品类型
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<CommodityType> GetCommodityTypeRemote(IQuery query)
        {
            String url = query.GetUrl() + "?token=" + GlobalCache.loginUser.access_token;
            String response = httpHelper.GetRequestJson(url);

            CommodityTypeResponse cres = jsonHelper.JsonDeSerializer<CommodityTypeResponse>(response);
            if (cres == null)
                cres = new CommodityTypeResponse() { isSuccess = false, message = "return data Exception" };

            List<model.CommodityType> list = new List<model.CommodityType>();
            if (cres.isSuccess)
                list.AddRange((CommodityType[])cres.GetData());

            return list;
        }

        public List<Commodity> GetCommoditysRemote(IQuery query)
        {
            String url = query.GetUrl() + "?token=" + GlobalCache.loginUser.access_token;
            String response = httpHelper.GetRequestJson(url);

            CommoditysResponse cres = jsonHelper.JsonDeSerializer<CommoditysResponse>(response);
            if (cres == null)
                cres = new CommoditysResponse() { isSuccess = false, message = "return data Exception" };

            List<model.Commodity> list = new List<model.Commodity>();
            if (cres.isSuccess)
                list.AddRange((Commodity[])cres.GetData());

            return list;
        }
    }



}
